package com.hillky.discovery.impl;

import com.hillky.Constant;
import com.hillky.ServiceConfig;
import com.hillky.discovery.AbstractRegistry;
import com.hillky.utils.NetUtils;
import com.hillky.utils.zookeeper.ZookeeperNode;
import com.hillky.utils.zookeeper.ZookeeperUtils;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooKeeper;

import java.net.InetSocketAddress;
import java.util.List;

public class NacosRegistry extends AbstractRegistry {

    private static   ZooKeeper zookeeper;

    public NacosRegistry() {
        zookeeper=ZookeeperUtils.createZookeeper();
    }

    public NacosRegistry(String connectString,int timeout) {
        this.zookeeper = ZookeeperUtils.createZookeeper(connectString,timeout);
    }

    public NacosRegistry(ZooKeeper zookeeper) {
        this.zookeeper = zookeeper;
    }

    @Override
    public void register(ServiceConfig<?> service) {
        //服务名称的节点
        String parentNode = Constant.BASE_PROVIDERS_PATH + "/" + service.getInterface().getName();

        //创建父亲持久节点
        if(!ZookeeperUtils.exists(zookeeper,parentNode,null)){
            ZookeeperNode zookeeperNode = new ZookeeperNode(parentNode, null);
            ZookeeperUtils.createNode(zookeeper,zookeeperNode,null, CreateMode.PERSISTENT);
        }

        //创建临时节点
        //节点名称: ip+端口
        String node = parentNode + "/" + NetUtils.getIp() + ":8088" ;
        //创建子节点
        if(!ZookeeperUtils.exists(zookeeper,node,null)){
            ZookeeperNode zookeeperNode = new ZookeeperNode(node, null);
            ZookeeperUtils.createNode(zookeeper,zookeeperNode,null, CreateMode.PERSISTENT);
        }

    }

    @Override
    public List<InetSocketAddress> lookup(String name,String group) {
        return null;
    }
}
